package com.jkoss.wine.customer.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jkoss.base.controller.BaseController;
import com.jkoss.common.util.CommonUtil;
import com.jkoss.common.util.Constant;
import com.jkoss.common.util.CryptoUtils;
import com.jkoss.common.util.ExcelUtiles;
import com.jkoss.common.vo.DwzPageBean;
import com.jkoss.wine.customer.entity.Shop;
import com.jkoss.wine.customer.service.IProductInventoryService;
import com.jkoss.wine.customer.service.IShopService;
import com.jkoss.wine.customer.vo.ShopVo;
import com.jkoss.wine.investment.entity.Investment;
import com.jkoss.wine.system.entity.Areas;
import com.jkoss.wine.system.entity.MerchantEmployees;
import com.jkoss.wine.system.service.IAreasService;

/**
 * 店铺 前端控制器
 * 
 * @Author Jason
 * @Version 1.0, 2019-08-12
 * @See
 * @Since com.jkoss.wine.customer.controller
 * @Description: TODO
 */
@MultipartConfig
@Controller
@RequestMapping("/customer/shop")
public class ShopController extends BaseController {

	@Autowired
	private IShopService iShopService;
	@Autowired
	private IAreasService iAreasService;
	@Autowired
	private IProductInventoryService iProductInventoryService;

	@RequestMapping("/list")
	@RequiresPermissions("/customer/shop/list")
	public String list(String shopName, String areaName, Date fwtm, HttpServletRequest request,
			HttpServletResponse response, ModelMap map, DwzPageBean dwzPageBean) {
		dwzPageBean.getCountResultMap().put("shopName", shopName);
		dwzPageBean.getCountResultMap().put("areaName", areaName);
		dwzPageBean.getCountResultMap().put("fwtm", fwtm);
		Wrapper wrapper = Condition.create().ne("s.del", 1).like("s.shop_name", shopName).like("s.area_name",
				areaName)/* .eq("f.fwtm", fwtm) */;
		if (!CommonUtil.isBlank(dwzPageBean.getOrderField()) && !CommonUtil.isBlank(dwzPageBean.getOrderDirection())) {
			dwzPageBean.getCountResultMap().put("orderField", dwzPageBean.getOrderField());
			dwzPageBean.getCountResultMap().put("orderDirection", dwzPageBean.getOrderDirection());
			wrapper.orderBy(dwzPageBean.getOrderField(), CommonUtil.isEquals(dwzPageBean.getOrderDirection(), "asc"));
		} else {
			wrapper.orderBy("sfwtm", false);
		}

		Page<Shop> resultPage = iShopService.selectVoByPage(dwzPageBean.toPage(), wrapper);
		map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));
		return "customer/customer/list";

	}

	@RequestMapping("/toInsert")
	@RequiresPermissions("/customer/shop/toInsert")
	public String toInsert(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		Wrapper wrapper2 = Condition.create().like("id", "%0000");
		List<Investment> province = iAreasService.selectList(wrapper2);
		map.put("province", province);
		return "customer/customer/edit";

	}

	@RequestMapping("/insert")
	@RequiresPermissions("/customer/shop/toInsert")
	@ResponseBody
	public Object insert(Shop shop, HttpServletRequest request, HttpServletResponse response) {
		shop.setDel(0);
		shop.setAddTime(CommonUtil.getDate());
		shop.setOperatingPwd(CryptoUtils.encodeMD5("88888888"));
		shop.setBelongs("aaaaaaaaaaaaaaaa");
		MerchantEmployees merchantEmployees = (MerchantEmployees) SecurityUtils.getSubject().getSession(true)
				.getAttribute(Constant.SESSION_USER_KEY);
		String operator = merchantEmployees.getEmployeeId();
		shop.setOperator(operator);
		
		Wrapper wrapper = Condition.create().eq("mobile_phone", shop.getMobilePhone());
		if(iShopService.selectCount(wrapper)>0) {
			System.out.println("存在客户");
			return ajaxError();
		}
		if (iShopService.insert(shop)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}

	}

	@RequestMapping("/toUpdate")
	@RequiresPermissions("/customer/shop/toUpdate")
	public String toUpdate(String id, HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		Shop shop = iShopService.selectById(id);
		map.put("record", shop);

		Wrapper wrapper2 = Condition.create().like("id", "%0000");
		List<Investment> province = iAreasService.selectList(wrapper2);
		map.put("province", province);
		String areaCode = shop.getAreaCode();
		if (areaCode.equals(",,")) {
			return "customer/customer/edit";
		}
		String[] str = areaCode.split(",");
		for (String string : str) {
			System.out.println("----------------------------------------------------------------------------------");
			System.out.println(string);
		}
		Wrapper wrapper3 = Condition.create().like("id", str[1].substring(0, 2) + "%00").ne("id", str[0]);
		List<Areas> city = iAreasService.selectList(wrapper3);
		map.put("city", city);

		Wrapper wrapper4 = Condition.create().ne("id", str[1]).like("id", str[1].substring(0, 4) + "%");
		List<Areas> region = iAreasService.selectList(wrapper4);
		map.put("region", region);

		map.put("provinceid", str[0]);
		map.put("cityid", str[1]);
		map.put("regionid", str[2]);
		return "customer/customer/edit";
	}

	@RequestMapping("/update")
	@RequiresPermissions("/customer/shop/toUpdate")

	@ResponseBody
	public Object update(Shop shop, HttpServletRequest request, HttpServletResponse response) {
		Wrapper wrapper = Condition.create().eq("mobile_phone", shop.getMobilePhone());
		if(iShopService.selectCount(wrapper)>0) {
			System.out.println("存在客户");
			return ajaxError();
		}
		if (iShopService.updateById(shop)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	@RequestMapping("/delete")
	@RequiresPermissions("/customer/shop/delete")
	@ResponseBody
	public Object delete(String[] id, HttpServletRequest request, HttpServletResponse response) {
		List list = new ArrayList();
		for (String str : id) {
			Shop shop = iShopService.selectById(str);
			shop.setDel(1);
			list.add(shop);
		}
		if (iShopService.updateBatchById(list)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	@RequestMapping("/excelExport")
	@RequiresPermissions("/customer/shop/excelExport")
	public void excelExport(String shopName, String areaName, DwzPageBean dwzPageBean, HttpServletRequest request,
			HttpServletResponse response) {
		Wrapper wrapper = Condition.create().ne("s.del", 1).like("s.shop_name", shopName).like("s.area_name", areaName);
		if (!CommonUtil.isBlank(dwzPageBean.getOrderField()) && !CommonUtil.isBlank(dwzPageBean.getOrderDirection())) {
			dwzPageBean.getCountResultMap().put("orderField", dwzPageBean.getOrderField());
			dwzPageBean.getCountResultMap().put("orderDirection", dwzPageBean.getOrderDirection());
			wrapper.orderBy(dwzPageBean.getOrderField(), CommonUtil.isEquals(dwzPageBean.getOrderDirection(), "asc"));
		} else {
			wrapper.orderBy("add_time", false);
		}
		ExcelUtiles.exportExcel(iShopService.selectVo(wrapper), "常规客户信息列表", "常规客户", ShopVo.class, "客户信息.xls", response);
	}

	@RequestMapping("/excelParser")
	@RequiresPermissions("/customer/shop/excelParser")
	@ResponseBody
	public Object excelParser(MultipartFile file, HttpServletRequest request, HttpServletResponse response)
			throws IllegalStateException, IOException {

		List<Shop> list = ExcelUtiles.importExcel(file, 1, 1, Shop.class);

		log.debug(JSON.toJSONString(list));

		List<Shop> list2 = new ArrayList<Shop>();

		for (Shop shop : list) {
			if (!CommonUtil.isBlank(shop) && !CommonUtil.isBlank(shop.getShopName())) {
				Wrapper wrapper = Condition.create().eq("shop_num",shop.getShopNum()).or().eq("shop_name",shop.getShopName()).or().eq("contact_number", shop.getContactNumber()).or().eq("mobile_phone", shop.getMobilePhone());
				if(iShopService.selectCount(wrapper)>0) {
					return ajaxError();
				}
				shop.setAddTime(CommonUtil.getDate());
				shop.setDel(0);
				shop.setOperator(getUserId());
				shop.setOperatingPwd(CryptoUtils.encodeMD5("88888888"));
				list2.add(shop);
			}
		}
		log.debug(JSON.toJSONString(list2));
		if (iShopService.insertBatch(list2)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}

	}

	@RequestMapping("/toUpload")
	@RequiresPermissions("/customer/shop/excelParser")
	public String toUpload() {
		return "customer/customer/upload";
	}

}
